package com.ahaoyou.job;

import com.ahaoyou.entity.SysJob;
import com.ahaoyou.entity.SysJobLog;
import com.ahaoyou.service.SysJobLogService;
import com.ahaoyou.utils.ExceptionUtil;
import com.ahaoyou.utils.ScheduleConstants;
import com.ahaoyou.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;

/**
 * @author LH
 * @create 2022/3/8 16:54
 */
@Slf4j
public abstract class AbstractQuartzJob implements Job {

    /**
     * 定义线程时间变量 用于记录执行时间
     */
    ThreadLocal<Date> dateThreadLocal = new ThreadLocal<Date>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        SysJob sysJob = (SysJob) context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES);
        try {
            before(context, sysJob);
            if (sysJob != null) {
                doExecute(context, sysJob);
            }
            after(context, sysJob, null);
        } catch (Exception e) {
            log.error("任务执行异常  - ：", e);
            after(context, sysJob, e);
        }
    }

    /**
     * 执行之前
     *
     * @param context 工作执行上下文对象
     * @param job     系统计划任务
     */
    private void before(JobExecutionContext context, SysJob job) {
        dateThreadLocal.set(new Date());
    }


    /**
     * 执行之后
     *
     * @param context 工作执行上下文对象
     * @param job     系统计划任务
     * @param e       异常
     */
    private void after(JobExecutionContext context, SysJob job, Exception e) {
        SysJobLog sysJobLog = new SysJobLog();
        Date startTime = dateThreadLocal.get();
        dateThreadLocal.remove();
        sysJobLog.setJobName(job.getJobName());
        sysJobLog.setJobGroup(job.getJobGroup());
        sysJobLog.setInvokeTarget(job.getInvokeTarget());
        sysJobLog.setStartTime(startTime);
        sysJobLog.setStopTime(new Date());
        long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
        sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");
        if (e != null) {
            sysJobLog.setStatus("1");
            String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
            sysJobLog.setExceptionInfo(errorMsg);
        } else {
            sysJobLog.setStatus("0");
        }
        SpringContextHolder.getBean(SysJobLogService.class).save(sysJobLog);
    }

    /**
     * 具体执行的方法
     *
     * @param context 工作执行上下文对象
     * @param job     系统计划任务
     * @throws
     */
    protected abstract void doExecute(JobExecutionContext context, SysJob job) throws Exception;
}
